/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.me.nicefotoappcamp.provider;

import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import java.io.ByteArrayInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

/**
 *
 * @author Tadas
 */
public abstract class HttpProvider implements Provider {

    private HttpClient httpclient = new DefaultHttpClient();
    
    public String request(String url) {
        HttpGet httpget = new HttpGet(url);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = "";
        try {
            responseBody = getHttpclient().execute(httpget, responseHandler);
        } catch (IOException ex) {
            Logger.getLogger(HttpProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
        return responseBody;
    }

    public byte[] getFile(String url) {
        HttpGet method = new HttpGet(url);
        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {

            public byte[] handleResponse(
                    HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] response = null;
        try {
            response = getHttpclient().execute(method, handler);
        } catch (IOException ex) {
            Logger.getLogger(HttpProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
        return response;
    }

    public static Drawable pictureToDrawable(byte[] file) {
        return new BitmapDrawable(new ByteArrayInputStream(file));
    }


    /**
     * @return the httpclient
     */
    public HttpClient getHttpclient() {
        return httpclient;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        getHttpclient().getConnectionManager().shutdown();
    }



}
